package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.common.BaseContext;
import com.itheima.common.PaginationVO;
import com.itheima.dto.EssayDTO;
import com.itheima.entity.Essay;
import com.itheima.entity.YddEssay;
import com.itheima.mapper.EssayMapper;
import com.itheima.vo.EssayVO;
import com.itheima.service.EssayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class EssayServiceImpl implements EssayService {
    private final EssayMapper essayMapper;

    public EssayServiceImpl(EssayMapper essayMapper) {
        this.essayMapper = essayMapper;
    }

    @Override
    public PaginationVO<EssayVO> page(String page, String limit, String startTime, String endTime, String title, String cateid) {
        PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(limit));
        List<YddEssay> essays = essayMapper.list(startTime, endTime, title, cateid);
        System.out.println(essays);
        PageInfo<YddEssay> pageInfo = new PageInfo<>(essays);
        long count = pageInfo.getTotal();
        int totalPages = pageInfo.getPages();
        int pageSize = pageInfo.getPageSize();
        int currentPage = pageInfo.getNextPage();
        List<YddEssay> essayList = pageInfo.getList();

        List<EssayVO> essayVOList = new ArrayList<>();
        essayList.forEach(essay -> essayVOList.add(essay.getEssayVO()));

        PaginationVO<EssayVO> paginationVO = new PaginationVO<>();
        paginationVO.setCount(count);
        paginationVO.setTotalPages(totalPages);
        paginationVO.setPageSize(pageSize);
        paginationVO.setCurrentPage(currentPage);
        paginationVO.setData(essayVOList);
        return paginationVO;
    }

    @Override
    public EssayVO rowInfoEssayVO(String id) {
        Essay essay = essayMapper.rowInfoEssayVO(id);
        EssayVO essayVO = essay.getEssayVO();
        return essayVO;
    }

    @Override
    public void delEssayVO(String id) {
        essayMapper.delEssayVO(id);
    }

    @Override
    public void addEssay(EssayDTO essayVO) {
        Essay essay = essayVO.getEssayVO();
        int i = Integer.parseInt(BaseContext.getLoginUserId());
        essay.setUserId(i);
        essay.setDefaultData("1");
        essay.setStatus(2);
        essayMapper.addEssay(essay);
    }

    @Override
    public void updateEssay(EssayDTO essayVO) {
        Essay essay = essayVO.getEssayVO();
        essayMapper.updateEssay(essay);
    }
}
